export default defineEventHandler(async (event) => {
  const res = await MenuSchema.find().sort({ order: 1 }).lean();

  let flatData = res.map((item: any) => {
    item.id = item._id;
    item.label = item.name;
    return item;
  });

  let tree = convertToTree(flatData);

  return {
    data: tree,
  };
});

interface Tree {
  id: number;
  label: string;
  name: string;
  path: string;
  icon?: string;
  order?: number;
  parentId?: number;
  children?: Tree[];
}

// 扁平数组转换为树结构
function convertToTree(data: Tree[]): Tree[] {
  const map: { [key: string]: Tree } = {};
  const tree: Tree[] = [];

  // 先将每个节点存储到 map 中
  data.forEach((item) => {
    map[item.id] = { ...item, children: [] };
  });

  // 构建树结构
  data.forEach((item) => {
    if (item.parentId) {
      const parent = map[item.parentId];
      if (parent) {
        parent.children?.push(map[item.id]);
      }
    } else {
      tree.push(map[item.id]);
    }
  });

  return tree;
}
